package com.hxkj.shiro;


import com.hxkj.domain.po.AuthUser;
import com.hxkj.service.FunctionService;
import com.hxkj.service.RoleService;
import com.hxkj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;


@Slf4j
public class ServiceRealm extends AuthorizingRealm {

    @Autowired
    private FunctionService functionService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String account = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 查询角色
        try {
            Set<String> roles = roleService.findRolesByAccount(account);
            authorizationInfo.setRoles(roles);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("realm设置用户角色失败:{}", e.getMessage());
        }
        // 查询功能
        try {
            Set<String> functions = functionService.findPermissionsByAccount(account);
            authorizationInfo.setStringPermissions(functions);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("realm设置用户权限失败:{}", e.getMessage());
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        StatelessToken statelessToken = (StatelessToken) token;
        String userToken = statelessToken.getToken();
        // 根据token获取用户信息
        AuthUser authUser;
        try {
            authUser = userService.getUserInfoByToken(userToken);
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(authUser.getUserAccount(), userToken, getName());
            return simpleAuthenticationInfo;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthenticationException("根据token获取用户信息失败");
        }
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        // 仅支持StatelessToken类型的Token
        return token instanceof StatelessToken;
    }

}
